﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using LeanEngine.Entity;

namespace LeanEngine.Data
{
    internal static class DataCommandExtensions
    {
        internal static void AcquireConnection(this IDataCommand command)
        {
            if (DataTransactionPool.HasTransaction())
            {
                var trans = DataTransactionPool.GetTransaction();
                command.Transaction = trans.Transaction;
                command.Connection = trans.Connection;
                command.Transaction = trans.Transaction; //Wordkaround bug de não setar na primera linha com o mysql
            }
            else
            {
                command.Connection = DataProvider.NewConnection();
                command.Connection.Open();
            }
        }

        internal static void ReleaseConnection(this IDataCommand command)
        {
            if (command.Transaction == null &&
                command.Connection != null)
            {
                command.Connection.Close();
                command.Connection.Dispose();
                command.Connection = null;
            }
        }

        public static List<T> ReadList<T>(this IDataCommand command, Action<T, IDataReader> mapAction)
            where T : PlainEntity, new()
        {
            command.AcquireConnection();

            try
            {
                var resultList = new List<T>();
                using (var resultSet = command.ExecuteReader())
                {
                    while (resultSet.Read())
                    {
                        var item = new T();
                        mapAction.Invoke(item, resultSet);
                        resultList.Add(item);
                    }
                }

                return resultList;
            }
            finally
            {
                command.ReleaseConnection();
            }
        }
    }
}
